package com.example.community.provider;

import com.alibaba.fastjson.JSON;
import com.example.community.model.dto.AccessTokenDTO;
import com.example.community.provider.dto.GithubUserDTO;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class GithubProvider {
    /**
     * 获取access_token
     * @param accessTokenDTO github的access_token接口需要的5个参数
     * @return access_token
     */
    public String getAccessToken(AccessTokenDTO accessTokenDTO) {

        // 调用github的access_token接口，使用第三方工具okhttp
        // okhttp文档：https://square.github.io/okhttp/
        MediaType mediaType = MediaType.get("application/json");

        OkHttpClient client = new OkHttpClient();

        // 使用fastjson把accessTokenDTO一个java快速变成json
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));

        Request request = new Request.Builder()
                .url("https://github.com/login/oauth/access_token")
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();

            /* 文档中的样例：
            access_token=gho_16C7e42F292c6912E7710c838347Ae178B4a&scope=repo%2Cgist&token_type=bearer
            所以通过&分割获得前半部分，通过=分割获得access_token */
            String token = string.split("&")[0].split("=")[1];
            return token;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 通过得到的access_token获取用户信息
     * @param accessToken 获取的access_token
     * @return 用户信息
     */
    public GithubUserDTO getUser(String accessToken) {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.github.com/user" )
                .addHeader("Authorization", "Bearer " + accessToken)
                .build();

        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            // 通过fastjson把json转成java类对象
            GithubUserDTO githubUser = JSON.parseObject(string, GithubUserDTO.class);
            return githubUser;
        } catch (IOException e) {
        }
        return null;
    }
}
